(function ($) {
    $.fn.zgdGridView = function (method) {
        if (method.selectCheckedRows) {
            return methods.selectCheckedRows.apply(this, Array.prototype.slice.call(arguments, 0));
        }else {
            $.error('Method ' + method + ' does not exist on jQuery.zgdGridView');
            return false;
        }
    };
    
    var methods = {
        selectCheckedRows: function (options) {
            var id = $(this).prop('id');
            options = options.selectCheckedRows;
            var table = $('.yiiGridView', '#' + id + ' .' + options.tableClass)
            if (!options.multiple) {
                return;
            }
            $(document).on('click.yiiGridView', '#' + id + ' .' + options.tableClass + ' > tbody > tr', function (e) {
                var $currentGrid, $row, isRowSelected, $checks,
                    $target = $(e.target);

                if ($target.closest('td').is('.empty,.button-column') || (e.target.type === 'checkbox' && !$target.hasClass('select-on-check'))) {
                    return;
                }

                $row = $(this);
                $currentGrid = $('#' + id);
                $checks = $('td.select-on-check input', $currentGrid);
                isRowSelected = $row.toggleClass('selected').hasClass('selected');

                $('td.select-on-check input', $row).prop('checked', isRowSelected);
                $("input.select-on-check-all", $currentGrid).prop('checked', $checks.length === $checks.filter(':checked').length);

                if (options.selectionChanged !== undefined) {
                    options.selectionChanged(id);
                }
            });
            
            $(document).on('click.yiiGridView', '#' + id + ' .' + options.tableClass + ' > tbody > tr > td.select-on-check input',function(e){
                $(this).closest('tr').toggleClass('selected');
            });
        },
    };
})(window.jQuery);
